package com.hy.admin.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hy.admin.enums.EnumPayModel;
import com.hy.admin.helper.request.TradeRequest;
import com.hy.admin.service.PayService;
import com.hy.core.request.ApiRequestDTO;
import com.hy.core.response.ApiResponseDTO;
import com.hy.core.response.ServicesResult;
import com.hy.utils.HyRequestHandler;
import org.apache.commons.httpclient.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by wayne on 18/4/22.
 */
@RestController
@RequestMapping("/api/pay")
public class PayController {
    protected final Logger logBase = LoggerFactory.getLogger(PayController.class);

    @Autowired
    protected PayService payService;

    @RequestMapping(value = "/placeOrder", method = RequestMethod.POST)
    public ApiResponseDTO placeOrder(@RequestBody ApiRequestDTO apiRequestDTO, HttpServletRequest request) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        logBase.info("placeOrder_request:{}", gson.toJson(apiRequestDTO));
        ApiResponseDTO apiResponseDTO = new ApiResponseDTO(HttpStatus.SC_ACCEPTED, "", apiRequestDTO.getUuid());
        TradeRequest tradeRequest = gson.fromJson(apiRequestDTO.getRequestData(), TradeRequest.class);

        if(tradeRequest.getPayMode() == EnumPayModel.WECHAT_JSAPIPAY.getId()){
            tradeRequest.setRequestIp(request.getRemoteAddr());
        }

        String domain = request.getScheme()+"://"+ request.getServerName()+request.getContextPath();

        ServicesResult<String> servicesResult = payService.confirmOrder(tradeRequest, domain);

        apiResponseDTO.initServicesResult(servicesResult);
        apiResponseDTO.setResponseData(gson.toJson(servicesResult.getResult()));
        logBase.info("placeOrder_response:{}", gson.toJson(apiResponseDTO));
        return apiResponseDTO;
    }

    @RequestMapping(value = "/queryOrder", method = RequestMethod.POST)
    public ApiResponseDTO queryOrder(@RequestBody ApiRequestDTO apiRequestDTO) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        logBase.info("queryOrder_request:{}", gson.toJson(apiRequestDTO));
        ApiResponseDTO apiResponseDTO = new ApiResponseDTO(HttpStatus.SC_ACCEPTED, "", apiRequestDTO.getUuid());
        TradeRequest tradeRequest = gson.fromJson(apiRequestDTO.getRequestData(), TradeRequest.class);

        ServicesResult<String> servicesResult = payService.queryOrder(tradeRequest);

        apiResponseDTO.initServicesResult(servicesResult);
        apiResponseDTO.setResponseData(gson.toJson(servicesResult.getResult()));
        logBase.info("queryOrder_response:{}", gson.toJson(apiResponseDTO));
        return apiResponseDTO;
    }

    @RequestMapping(value = "/wechartback", method = RequestMethod.POST)
    public void  wechartNotifyUrl(HttpServletResponse response, HttpServletRequest request){
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            logBase.debug("wechart back msg：{}", sb.toString());

            Map mapResult = HyRequestHandler.doXMLParse(sb.toString());
            payService.handlerOrder(mapResult);
            //回传微信
            response.setContentType("text/plain");
            response.setCharacterEncoding("utf-8");
            final PrintWriter writer = response.getWriter();
            String xmlResult = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            writer.write(xmlResult);
            writer.flush();
            writer.close();
        }catch (Exception ex){
            logBase.error("wechartback",ex);
        }
    }
}
